package com.zhiyou.aifeng.smart_machine

import android.annotation.SuppressLint
import android.os.Build
import android.os.Bundle
import com.alibaba.android.arouter.launcher.ARouter
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.animators.AnimationType
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.style.PictureWindowAnimationStyle
import com.zhiyou.aifeng.common.base.makeCall
import com.zhiyou.aifeng.common.base.oneClick
import com.zhiyou.aifeng.common.base.visible
import com.zhiyou.aifeng.common.helper.get
import com.zhiyou.aifeng.common.helper.getString
import com.zhiyou.aifeng.common.helper.putShared
import com.zhiyou.aifeng.common_ui.base.BaseActivity
import com.zhiyou.aifeng.common_ui.base.loadCircleImage
import com.zhiyou.aifeng.common_ui.model.BaseUrl
import com.zhiyou.aifeng.common_ui.oss.OSSHelper
import com.zhiyou.aifeng.common_ui.oss.scaleImage
import com.zhiyou.aifeng.common_ui.router.Routers
import com.zhiyou.aifeng.common_ui.utils.bindLifeCycle
import com.zhiyou.aifeng.common_ui.utils.showHintDialog
import com.zhiyou.aifeng.common_ui.utils.subscribeByNoError
import com.zhiyou.aifeng.common_ui.viewmodel.BaseViewModel
import com.zhiyou.aifeng.utils.GlideCacheUtil
import com.zhiyou.aifeng.utils.GlideEngine
import com.zhiyou.aifeng.utils.PictureSelectConst
import com.zhiyou.aifeng.utils.callback
import com.zhiyou.aifeng.viewmodel.SettingViewModel
import kotlinx.android.synthetic.main.activity_setting.*
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast

class SettingActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_setting)
        initTitle(title = "我的设置", divider = false)

        getData()
    }

    override fun getViewModel() = get<SettingViewModel>()

    @SuppressLint("SetTextI18n")
    override fun initTitle(title: String, name: String, divider: Boolean) {
        super.initTitle(title, name, divider)
        setting_img.loadCircleImage(getString("userHead").scaleImage())
        setting_cache.setRightString(GlideCacheUtil.getInstance().getAllCacheSize(baseContext))
        setting_service.setRightString(getString("serviceTel"))
        setting_version.text = "v${BaseViewModel.mVersion}"

        setting_img_ll.oneClick { openGallery() }
        setting_version_ll.oneClick { getViewModel().checkUpdate(this) }
        setting_feedback.oneClick { startActivity<FeedbackActivity>() }
        setting_cache.oneClick {
            showHintDialog(
                title = "清空缓存",
                hint = "确定要清空缓存吗？"
            ) {
                GlideCacheUtil.getInstance().clearImageAllCache(baseContext)
                setting_cache.setRightString("0B")
            }
        }
        setting_about.oneClick {
            ARouter.getInstance()
                .build(Routers.deal)
                .withString("title", "关于我们")
                .navigation()
        }
        setting_deal.oneClick {
            ARouter.getInstance()
                .build(Routers.deal)
                .withString("title", "用户协议")
                .navigation()
        }
        setting_secret.oneClick {
            ARouter.getInstance()
                .build(Routers.deal)
                .withString("title", "隐私政策")
                .navigation()
        }
        setting_service.oneClick {
            if (getString("serviceTel").isNotEmpty()) {
                showHintDialog(
                    title = "提示",
                    hint = "确定要拨打客服电话吗？"
                ) { makeCall(getString("serviceTel")) }
            }
        }
        bt_quit.oneClick {
            showHintDialog(
                title = "退出登录",
                hint = "确定要退出当前账户？"
            ) {
                ARouter.getInstance()
                    .build(Routers.login)
                    .withBoolean("offLine", true)
                    .navigation()
            }
        }
    }

    private fun openGallery() {
        PictureSelector.create(this)
            // 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
            .openGallery(PictureMimeType.ofImage())
            // 外部传入图片加载引擎，必传项
            .imageEngine(GlideEngine.createGlideEngine())
            // 主题样式设置
            .theme(R.style.Picture_Green_Style)
            // 是否开启微信图片选择风格
            .isWeChatStyle(false)
            // 是否使用自定义相机，仿微信朋友圈
            .isUseCustomCamera(false)
            // 自定义相册启动退出动画
            .setPictureWindowAnimationStyle(PictureWindowAnimationStyle())
            // 列表动画效果
            .setRecyclerAnimationMode(AnimationType.DEFAULT_ANIMATION)
            // 选择数到了最大阀值列表是否启用蒙层效果
            .isMaxSelectEnabledMask(false)
            // 最大图片选择数量
            .maxSelectNum(1)
            // 多选 or 单选
            .selectionMode(PictureConfig.SINGLE)
            // 是否显示拍照按钮
            .isCamera(true)
            .apply {
                if (Build.BRAND == "LeEco"
                    && Build.VERSION.SDK_INT < Build.VERSION_CODES.Q
                ) {
                    // 自定义相机输出目录只针对Android Q以下版本
                    setOutputCameraPath(PictureSelectConst.getSavePath())
                }
            }
            // 是否显示gif图片
            .isGif(false)
            // 是否压缩
            .isCompress(true)
            // 是否裁剪
            .isEnableCrop(true)
            // 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
            .withAspectRatio(1, 1)
            // 是否显示uCrop工具栏，默认不显示
            .hideBottomControls(true)
            // 是否圆形裁剪
            .circleDimmedLayer(true)
            // 是否显示裁剪矩形边框 圆形裁剪时建议设为false
            .showCropFrame(false)
            // 是否显示裁剪矩形网格 圆形裁剪时建议设为false
            .showCropGrid(false)
            // 是否开启点击声音
            .isOpenClickSound(false)
            // 裁剪输出质量 默认100
            .cutOutQuality(90)
            // 小于多少kb的图片不压缩
            .minimumCompressSize(100)
            .callback {
                onResult {
                    val media = it[0]

                    OSSHelper.manager.uploadImage(
                        path = if (media.isCompressed) media.compressPath else media.cutPath,
                        onBefore = { showLoading("正在上传中...") },
                        onAfter = { dismissLoading() },
                        onSuccess = { result ->
                            val mUrl = result.responseHeader["url"].orEmpty()
                            getViewModel().request(
                                requestUrl = BaseUrl.avatar,
                                params = *arrayOf(
                                    "uid" to getString("userId"),
                                    "avatar" to mUrl
                                ),
                                onResult = {
                                    toast("修改头像成功！")

                                    putShared("userHead", mUrl)
                                    setting_img.loadCircleImage(mUrl.scaleImage())
                                }
                            )
                        },
                        OnError = { toast("网络异常，请稍候再试！") }
                    )
                }
            }
    }

    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel().getVersion()
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByNoError(
                event = getViewModel(),
                toast = false,
                onSuccess = {
                    setting_version_img.visible()
                }
            )
    }

}